﻿param(
	[Parameter(Mandatory=$true)]
    [string] $PatPathSrc = "."
  )
#$DebugPreference = "slientlycontinue"
$patPath = $PatPathSrc+'-Renamed'+(Get-Date -Format 'yyyyMMddHHmmss')
#创建目录到工作目录
if(!(Test-Path $patPath)){
    New-Item -Path $patPath -Force -ItemType Directory
}else{
    Remove-Item -Path $patPath -Force
}

Get-ChildItem -Path $PatPathSrc -Filter "*.xml" | %{
    Copy-Item -Path $_.FullName -Recurse -Destination $patPath -Force
    Write-Host $_.FullName
}

$patName = (Get-Item -Path $patPath).BaseName
if($patName -match "([\u4e00-\u9fa5]+)"){
	$patName = $matches[1]
}else{
	Exit 1
}
$files = @{}
Get-ChildItem -Path $patPath -Filter "*.xml" | %{
  if($_.BaseName -match "([\u4e00-\u9fa5]+)"){
 	$doc_name = $matches[1]
	if ($files.Keys -notcontains $doc_name){
 		$files[$doc_name]=1
 	}else{
		$files[$doc_name]=$files[$doc_name] + 1
	}
 }
}

Get-ChildItem -Path $patPath  -Filter "*.xml" | %{
	$doc_name=""
	$doc_num=[System.Int32]0
	$doc_prefix="EMR-SD"
	$doc_file_str_ctn_num= $false
	$doc_id=$_.BaseName.Substring(3,2)
	$doc_num_str="-"
	$extension = $_.Extension
	if($_.BaseName -match "([\u4e00-\u9fa5]+)"){
		$doc_name = $matches[1]
	}
	if($doc_name -eq "") {
		continue
	}	
	if($_.BaseName -match "\((\d+)\)" ){
		$doc_num = [System.Int32] $matches[1]
		$doc_file_str_ctn_num=$true
	}
 	$doc_num = [System.Int32]$doc_num +1
 	$doc_num_str="-{0}" -f $doc_num
#	#原文件中不含数字，并且同文件名数量<=1 的，文件编号取空字符串
#	if((-not $doc_file_str_ctn_num) -and ($files[$doc_name] -le 1)){
#		$doc_num_str = ""
#	}
	Write-Host ("{0}-{1}-{2}{3}-{4}{5}" -f $doc_prefix, $doc_id, $doc_name, $doc_num_str,$patName,$extension)
	Rename-Item -Path $_.FullName -NewName ("{0}-{1}-{2}{3}-{4}{5}" -f $doc_prefix, $doc_id, $doc_name, $doc_num_str,$patName,$extension)

}